package com.weichen.studentgameexchange.member.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.weichen.studentgameexchange.common.config.JwtConfig;
import com.weichen.studentgameexchange.member.dao.UserMapper;
import com.weichen.studentgameexchange.member.entity.User;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 功能：
 * 作者：惟尘
 * 日期：2025/1/23 20:18
 */
@Component
public class TokenUtils {

    private static UserMapper staticUserMapper;

    @Resource
    UserMapper userMapper;

    @PostConstruct
    public void setUserService() {
        staticUserMapper = userMapper;
    }

    /**
     * 生成token
     * @param userId 用户ID
     * @param password 密码
     * @return 生成的token字符串
     */
    public static String createToken(String userId, String password) {
        return JWT.create()
                .withAudience(userId) // 将userId保存到token里面，作为载荷
                .withSubject("User")  // 设置Subject
                .withExpiresAt(DateUtil.offsetHour(new Date(), 24)) // 2小时后token过期
                .sign(Algorithm.HMAC256("H4FX3kR7rBr5lALVUhmbwsLDNj05+UgaqT25lbmFDjw=")); // 使用从配置中获取的密钥
    }

    /**
     * 获取当前登录的用户信息
     * @return user对象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserMapper.selectById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
